//
//  KnowViewController.m
//  EMMApp
//
//  Created by Mac on 16/5/11.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "KnowViewController.h"
#import "KnowCell.h"
#import "NewFromViewController.h"
#import "KnowDetailsViewController.h"
#import "GetPayDepositListApi.h"

@interface KnowViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *knowTableView;

@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, assign) int currentPageSize;// 当前页码

@property (nonatomic, strong) UILabel *jlLabel; //当前没有记录

@property (nonatomic, strong) GetPayDepositList *getPayDepositList;

@end

@implementation KnowViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatNavigationController];
    self.customerStar.hidden = YES;
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#f5f5f5"];
     [self creathtTableView];
    _jlLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 300, EMM_WIDTH, 20)];
    _jlLabel.textAlignment = NSTextAlignmentCenter;
    _jlLabel.text = @"当前没有记录";
    _jlLabel.font = [UIFont systemFontOfSize:16];
    _jlLabel.hidden = YES;
    [self.view addSubview:_jlLabel];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _dataArr = [[NSMutableArray alloc] init];
    [self.knowTableView.mj_header beginRefreshing];    
}

#pragma mark - 初始化
- (void)creathtTableView {
    _knowTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50.5, EMM_WIDTH, EMM_HEIGHT-50.5-SafeAreaTopHeight) style:UITableViewStylePlain];
    _knowTableView.delegate = self;
    _knowTableView.dataSource = self;
    _knowTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _knowTableView.showsVerticalScrollIndicator = NO;
    _knowTableView.backgroundColor = [UIColor colorFromHexCode:@"#f5f5f5"];
    [self.view addSubview:_knowTableView];
    
    self.knowTableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
        
    }];
    self.knowTableView.mj_header.automaticallyChangeAlpha = YES;
    self.knowTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
}

#pragma mark 下拉刷新数据
- (void)loadNewData {
    [_dataArr removeAllObjects];
    _currentPageSize = 1;
    [self postGetCustomerListApiCurrentPageSize:_currentPageSize];
}

#pragma mark 上拉加载更多数据
- (void)loadMoreData {
    _currentPageSize = _currentPageSize + 1;
    [self postGetCustomerListApiCurrentPageSize:_currentPageSize];
}

#pragma mark - 结束刷新
- (void)endRefreshing {
    [self.knowTableView.mj_footer endRefreshing];
    [self.knowTableView.mj_header endRefreshing];
}

#pragma mark - 查询认筹列表接口
- (void)postGetCustomerListApiCurrentPageSize:(int)currentPageSize {
    [self showHud:@"正在加载请稍等..."];
    GetPayDepositListApi *api = [[GetPayDepositListApi alloc] initWithCustomerId:self.customerId pageNumber:currentPageSize pageSize:10];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetPayDepositListApi *result = (GetPayDepositListApi *)request;
        if (result.isSuccess) {
            GetPayDepositList *get = result.resultData;
            _getPayDepositList = get;
            for (PayDepositList *list in get.payDepositList) {
                [_dataArr addObject:list];
            }
            if (_dataArr.count > 0) {
                _jlLabel.hidden = YES;
            }else {
                _jlLabel.hidden = NO;
            }
            [self upTitleInitWith];
        } else {
//            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
        [self endRefreshing];
        [_knowTableView reloadData];
    } failure:^(YTKBaseRequest *request) {
        _knowTableView.hidden = YES;
        _jlLabel.hidden = NO;
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
        [self endRefreshing];
    }];
}

- (void)upTitleInitWith {
    self.userNameLabel.text = _getPayDepositList.customerName;
//    if ([NSString isStringEmpty2:_getCustomerDetail.customerStar] == NO) {
//        if ([_getCustomerDetail.customerStar isEqualToString:@"是"]) {
//            self.customerStar.hidden = NO;
//        }else {
//            self.customerStar.hidden = YES;
//        }
//    }
//    self.sexLabel.layer.masksToBounds = YES;
//    self.sexLabel.layer.cornerRadius = 5;
//    self.sexLabel.backgroundColor = [UIColor colorFromHexCode:@"#0fa1a1"];
//    self.sexLabel.text = _getCustomerDetail.customerSex;
//    self.gradeLabel.layer.masksToBounds = YES;
//    self.gradeLabel.layer.cornerRadius = 5;
//    self.gradeLabel.text = _getCustomerDetail.intentionLevel;
//    self.gradeLabel.backgroundColor = [UIColor colorFromHexCode:@"#3e5b5"];
    self.phoneLabel.text = _getPayDepositList.customerPhone;
}

#pragma mark - 导航
- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = @"认筹列表";
//    [self configLeftBtn];

    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:CGRectMake(0, 0, 54 ,44)];
    [backBtn addTarget:self
                action:@selector(NewbackToPreviousPage:)
      forControlEvents:UIControlEventTouchUpInside];
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn setImage:[UIImage imageNamed:@"ico_back"] forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    if (EMM_WIDTH <= 320) {
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }else if (EMM_WIDTH > 375){
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    }else{
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];

    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"icon_jia"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(KnowRightClick:)];
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *isAddPaydeposit =[userdf objectForKey:@"isAddPaydeposit"];
    if ([isAddPaydeposit isEqualToString:@"1"]) {
        [self.navigationItem setRightBarButtonItem:rightItme];
    }
    
//    UIButton *rightItme = [UIButton buttonWithType:UIButtonTypeCustom];
//    [rightItme setFrame:CGRectMake(0, 0, 54 ,44)];
//    [rightItme addTarget:self
//                  action:@selector(KnowRightClick:)
//        forControlEvents:UIControlEventTouchUpInside];
//    [rightItme setBackgroundColor:[UIColor clearColor]];
//    [rightItme setImage:[UIImage imageNamed:@"icon_jia"] forState:UIControlStateNormal];
//    rightItme.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [rightItme layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:0];
//    if (EMM_WIDTH <= 320) {
//        rightItme.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -5);
//    }else if (EMM_WIDTH > 375){
//        rightItme.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
//    }else{
//        rightItme.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -5);
//    }
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightItme];
    
}
- (void)NewbackToPreviousPage:(id) send {
    if (_newCustomersBlock) {
        _newCustomersBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)KnowRightClick:(UIButton *)btn  {
    NewFromViewController *nvc = [[NewFromViewController alloc] init];
    nvc.customerId = self.customerId;
    nvc.isFrom = @"0";
    [self.navigationController pushViewController:nvc animated:YES];
}

#pragma mark - UITableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"KnowCellId";
    KnowCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"KnowCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.knoeLabel.backgroundColor = [UIColor colorFromHexCode:@"#ff821c"];
    cell.statusLabel.backgroundColor = [UIColor colorFromHexCode:@"#ff821c"];
    
    if (_dataArr.count > 0) {
        PayDepositList *list = [_dataArr objectAtIndex:indexPath.row];
        
        cell.knowItmerLabel.text = list.payDepositTime;
        if ([NSString isStringEmpty2:list.payDepositHouses] == NO) {
//            NSString *strUrl = [list.payDepositHouses stringByReplacingOccurrencesOfString:@"-->" withString:@"-"];
            cell.knowNameLabel.text = list.payDepositHouses;
        }else {
            cell.knowNameLabel.text = @"无房";
        }
        [cell setSubscribeHouses:list.recordBusiness];
        if ([list.auditStatus isEqualToString:@"待提交"]) {
            cell.knowIMageView.image = [UIImage imageNamed:@"icon_submit"];
        }else if ([list.auditStatus isEqualToString:@"审核中"]) {
            cell.knowIMageView.image = [UIImage imageNamed:@"icon_revie"];
        }else if ([list.auditStatus isEqualToString:@"已退回"]) {
            cell.knowIMageView.image = [UIImage imageNamed:@"icon_back"];
        }else if ([list.auditStatus isEqualToString:@"已通过"]) {
            cell.knowIMageView.image = [UIImage imageNamed:@"icon_sucss"];
        }
        if ([list.auditStatus isEqualToString:@"已退回"]||[list.recordBusiness isEqualToString:@"认筹退房"]) {
            cell.knoeLabel.backgroundColor = [UIColor colorFromHexCode:@"#AAAAAA"];
            cell.statusLabel.backgroundColor = [UIColor colorFromHexCode:@"#AAAAAA"];
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArr.count > 0) {
        PayDepositList *list = [_dataArr objectAtIndex:indexPath.row];
        KnowDetailsViewController  *kvc = [[KnowDetailsViewController alloc] init];
        kvc.payDepositId = list.payDepositId;
        kvc.customerId = self.customerId;
        kvc.paymentMethod = self.paymentMethod;
        kvc.getCustomerDetail = _getCustomerDetail;
        kvc.isNot = YES;
        [self.navigationController pushViewController:kvc animated:YES];
    }
}

- (IBAction)phonKowbtnClick:(id)sender {
//    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];    
//    NSString *isPhoneInformation = [userdf objectForKey:@"isPhoneInformation"];
//    if ([NSString isStringEmpty2:isPhoneInformation] == NO) {
//        if ([isPhoneInformation isEqualToString:@"0"]) {
//            NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_getPayDepositList.customerPhone];
//            UIWebView * callWebview = [[UIWebView alloc] init];
//            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
//            [self.view addSubview:callWebview];
//
//        }else if ([isPhoneInformation isEqualToString:@"1"]) {

//        }
//    }else {
//        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_getPayDepositList.customerPhone];
//        UIWebView * callWebview = [[UIWebView alloc] init];
//        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
//        [self.view addSubview:callWebview];
//    }
    [self postGetUserCallListApi];
}

#pragma maek - 电话平台调用方法
- (void)postGetUserCallListApi {
    [self showHudInWindow:@"正在加载中..."];
    GetUserCallListApi *api = [[GetUserCallListApi alloc] initWith];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetUserCallListApi *result = (GetUserCallListApi *)request;
        //请求成功
        if (result.isSuccess) {
            GetUserCallList *get = result.resultData;
            if ([NSString isStringEmpty2:get.isPhoneInformation] == NO) {
                if ([get.isPhoneInformation isEqualToString:@"0"]) {
                    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_getPayDepositList.customerPhone];
                    UIWebView * callWebview = [[UIWebView alloc] init];
                    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                    [self.view addSubview:callWebview];
                }else {
                    UserCallMenuView *userListV = [[UserCallMenuView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT) title:@"选择拨打号码" nameArr:get.userCallList];
                    userListV.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
                    [[UIApplication sharedApplication].keyWindow addSubview:userListV];
                    __weak UserCallMenuView *weakMenuView = userListV;
                    [userListV setTouchUserCallMenuViewBlock:^(NSString *telePhone, NSString *telePhoneType) {
                        NSLog(@"%@-%@",telePhone,telePhoneType);
                        if ([NSString isStringEmpty2:telePhone] == NO) {
                            [self postGetCallBackApiTelePhoneString:telePhone];
                        }
                        [weakMenuView removeFromSuperview];
                    }];
                }
            }else {
                NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_getPayDepositList.customerPhone];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
            }
        } else {
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

- (void)postGetCallBackApiTelePhoneString:(NSString *)telePhoneString {
    
    GetCallBackApi *api = [[GetCallBackApi alloc] initWithCustomerId:self.customerId caller:telePhoneString called:_getPayDepositList.customerPhone terminalModel:@"0" terminalModelId:self.customerId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetCallBackApi *result = (GetCallBackApi *)request;
        //请求成功
        if (result.isSuccess) {
            GetCallBack *get = result.resultData;
            FollowUpViewController *fvc = [[FollowUpViewController alloc] init];
            fvc.customerId = self.customerId;
            fvc.followId = get.followId;
            [self.navigationController pushViewController:fvc animated:YES];
        } else {
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

@end
